﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace OpenRPOSMetro
{
    public sealed partial class PizzaDialog : Page
    {
        public event EventHandler CloseRequested;
        public int iParentMenuItemID;
        public ObservableCollection<OrderData> orderDataList = new ObservableCollection<OrderData>();
        Dictionary<string, int> dictMenuItems = new Dictionary<string, int>();
        ObservableCollection<ServiceReferenceOpenRPOS.MenuItem> SpecialtyMenuItemRecords = new ObservableCollection<ServiceReferenceOpenRPOS.MenuItem>();
        ServiceReferenceOpenRPOS.MenuItemOptionGroup currentMenuItemOptionGroup;
        ServiceReferenceOpenRPOS.MenuItemOptionGroup specialtyMenuItemOptionGroup = null;
        Popup dialogPopup;
        string strPizzaToppingHeader;
        double dblMultiplier;

        public PizzaDialog()
        {
            this.InitializeComponent();
        }

        public void init()
        {
            // Load the specialty pizza names...
            foreach (ServiceReferenceOpenRPOS.MenuItem mi in Globals.MenuItemRecords.Where(x => x.col_SpecialtyPizza))
            {
                cmbSpecialties.Items.Add(mi.col_FullName);
                SpecialtyMenuItemRecords.Add(mi);
            }
            // Select the top item
            cmbSpecialties.SelectedIndex = 0;
            // Get the correct options data
            currentMenuItemOptionGroup = Globals.MenuItemOptionGroupRecords.Where(x => x.col_MenuItemID == iParentMenuItemID).First();
        }
        private void btnDone_Click(object sender, RoutedEventArgs e)
        {
            // Close the dialog...
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }
        private void showToppingOptions()
        {
            // Create a new dialog to display the current topping options
            OptionDialog od = new OptionDialog();
            od.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            od.Height = Windows.UI.Xaml.Window.Current.Bounds.Height;
            Dictionary<string, bool> dictMenuItemChecked = new Dictionary<string, bool>();
            Dictionary<string, ServiceReferenceOpenRPOS.MenuItem> dictOptionItems = new Dictionary<string, ServiceReferenceOpenRPOS.MenuItem>();
            ServiceReferenceOpenRPOS.OptionGroup og = Globals.OptionGroupRecords.Where(x => x.col_ID == currentMenuItemOptionGroup.col_OptionGroupID).First();
            specialtyMenuItemOptionGroup = null;
            int specialtyMenuItemID = Globals.MenuItemRecords.Where(x => x.col_FullName == cmbSpecialties.SelectedValue.ToString()).First().col_ID;
            if (Globals.MenuItemOptionGroupRecords.Where(x => x.col_MenuItemID == specialtyMenuItemID).Count() > 0)
                specialtyMenuItemOptionGroup = Globals.MenuItemOptionGroupRecords.Where(x => x.col_MenuItemID == specialtyMenuItemID).First();
            dictOptionItems.Clear();
            bool isChecked=false;
            dictMenuItems.Clear();
            dictOptionItems.Clear();
            // Determine the number of options
            foreach (ServiceReferenceOpenRPOS.MenuOption mo in Globals.MenuOptionRecords.Where(x => x.col_OptionGroupID == currentMenuItemOptionGroup.col_OptionGroupID))
            {
                if (Globals.MenuItemRecords.Where(x => x.col_ID == mo.col_MenuItemID).Count() > 0)
                {
                    ServiceReferenceOpenRPOS.MenuItem mi = Globals.MenuItemRecords.Where(x => x.col_ID == mo.col_MenuItemID).First();
                    dictMenuItems.Add(mi.col_FullName, mi.col_ID);
                    dictOptionItems.Add(mi.col_FullName, mi);
                    isChecked = mo.col_Checked;
                    // Select default for specialties...
                    if (specialtyMenuItemOptionGroup!=null)
                        foreach (ServiceReferenceOpenRPOS.MenuOption smo in Globals.MenuOptionRecords.Where(x => x.col_OptionGroupID == specialtyMenuItemOptionGroup.col_OptionGroupID))
                        {
                            if (smo.col_MenuItemID == mo.col_MenuItemID)
                                isChecked = smo.col_Checked;
                        }
                    dictMenuItemChecked.Add(mi.col_FullName, isChecked);
                }
            }
            // Display options in alphabetical order
            var list = dictMenuItems.Keys.ToList();
            list.Sort();
            int cnt = 0;
            double dblScale = 2;
            double dblCheckboxHeight = Globals.k_dbl_checkbox_height;
            int iNumCols = ((list.Count() - 1) / Globals.k_int_max_options_per_column) + 1;
            int iCurrCol = 0;
            // Iterate over the options in the group
            foreach (var key in list)
            {
                // Double the size of the options for easier selection
                ScaleTransform st = new ScaleTransform();
                st.ScaleX = dblScale;
                st.ScaleY = dblScale;
                CheckBox cb = new CheckBox();
                cb.Content = key;
                cb.Height = dblCheckboxHeight;
                cb.Margin = new Thickness(Globals.k_dbl_button_spacing + (iCurrCol * Globals.k_dbl_option_group_width), 
                    (cnt * Globals.k_dbl_checkbox_height * dblScale) + Globals.k_dbl_checkbox_height, 0, 0);
                cb.Padding = new Thickness(Globals.k_dbl_option_padding, Globals.k_dbl_option_padding, 0, 0);
                cb.RenderTransform = st;
                cb.IsChecked = dictMenuItemChecked[key];
                cb.HorizontalAlignment = HorizontalAlignment.Left;
                cb.VerticalAlignment = VerticalAlignment.Top;
                od.addUIElement(cb);
                iCurrCol = (iCurrCol + 1) % iNumCols;
                cnt = (iCurrCol == 0) ? cnt + 1 : cnt;
            }
            // Size the dialog
            od.innerDialog.Width = (Globals.k_dbl_option_group_width * iNumCols) + (2 * Globals.k_dbl_button_spacing);
            cnt = (list.Count() < Globals.k_int_max_options_per_column) ? list.Count() : Globals.k_int_max_options_per_column;
            od.innerDialog.Height = dblScale * cnt * (og.col_Exclusive ? Globals.k_dbl_radio_button_height : Globals.k_dbl_checkbox_height) + Globals.k_dbl_option_group_min_height;
            od.CloseRequested += Dialog_CloseRequested;
            dialogPopup = new Popup();
            dialogPopup.Child = od;
            dialogPopup.IsOpen = true;
        }
        private void Dialog_CloseRequested(object sender, EventArgs e)
        {
            OptionDialog currentOptionDialog = (OptionDialog)dialogPopup.Child;
            OrderData od = new OrderData();
            dialogPopup.IsOpen = false;
            od.MenuItemName = strPizzaToppingHeader;
            od.MenuItemID = Globals.MenuItemRecords.Where(x => x.col_FullName == strPizzaToppingHeader).First().col_ID;
            orderDataList.Add(od);
            lvToppings.Items.Add(od);
            od = new OrderData();
            od.MenuItemName = cmbSpecialties.SelectedValue.ToString();
            od.MenuItemID = SpecialtyMenuItemRecords[cmbSpecialties.SelectedIndex].col_ID;
            od.Price = SpecialtyMenuItemRecords[cmbSpecialties.SelectedIndex].col_Price;
            od.DisplayPrice = SpecialtyMenuItemRecords[cmbSpecialties.SelectedIndex].col_Price.ToString("N");
            lvToppings.Items.Add(od);
            orderDataList.Add(od);
            lvToppings.ScrollIntoView(cmbSpecialties.SelectedValue);
            // Determine if any default specialty items are to be "excluded"
            foreach (UIElement uie in currentOptionDialog.innerDialog.Children)
            {
                if (uie.GetType().ToString().Contains("CheckBox"))
                {
                    CheckBox cb = (CheckBox)uie;
                    if (cb.IsChecked == false) // Not Selected
                    {
                        bool bExcludeOption = false;
                        if (specialtyMenuItemOptionGroup != null)
                        {
                            int iMenuItemID = dictMenuItems[cb.Content.ToString()];
                            foreach (ServiceReferenceOpenRPOS.MenuOption smo in Globals.MenuOptionRecords.Where(x => x.col_OptionGroupID == specialtyMenuItemOptionGroup.col_OptionGroupID))
                            {
                                if (smo.col_MenuItemID == iMenuItemID)
                                    bExcludeOption = true;
                            }
                        }
                        if (bExcludeOption)
                        {
                            od = new OrderData();
                            od.Exclude = true;
                            od.MenuItemName = "No " + cb.Content.ToString();
                            od.MenuItemID = dictMenuItems[cb.Content.ToString()];
                            orderDataList.Add(od);
                            lvToppings.Items.Add(od);
                            lvToppings.ScrollIntoView(od);
                        }
                    }
                }
            }
            // Identify additional selected items
            foreach (UIElement uie in currentOptionDialog.innerDialog.Children)
            {
                if (uie.GetType().ToString().Contains("CheckBox"))
                {
                    CheckBox cb = (CheckBox)uie;
                    if (cb.IsChecked == true) // Selected
                    {
                        bool bAddOption = true;
                        if (specialtyMenuItemOptionGroup != null)
                        {
                            int iMenuItemID=dictMenuItems[cb.Content.ToString()];
                            foreach (ServiceReferenceOpenRPOS.MenuOption smo in Globals.MenuOptionRecords.Where(x => x.col_OptionGroupID == specialtyMenuItemOptionGroup.col_OptionGroupID))
                            {
                                if (smo.col_MenuItemID == iMenuItemID)
                                    bAddOption = false;
                            }
                        }
                        if (bAddOption)
                        {
                            od = new OrderData();
                            od.MenuItemName = "Add " + cb.Content.ToString();
                            od.MenuItemID = dictMenuItems[cb.Content.ToString()];
                            od.Price = (decimal)((double)Globals.MenuItemRecords.Where(x => x.col_ID == od.MenuItemID).First().col_Price * dblMultiplier);
                            od.DisplayPrice = od.Price.ToString("N");
                            orderDataList.Add(od);
                            lvToppings.Items.Add(od);
                            lvToppings.ScrollIntoView(od);                            
                        }
                    }
                }
            }
        }
        private void btnWholeToppings_Click(object sender, RoutedEventArgs e)
        {
            strPizzaToppingHeader = Globals.k_str_pizza_whole;
            dblMultiplier = 1;
            // Show the toppings dialog...
            showToppingOptions();
        }

        private void btnLeftToppings_Click(object sender, RoutedEventArgs e)
        {
            strPizzaToppingHeader = Globals.k_str_pizza_first_half;
            dblMultiplier = 0.5;
            // Show the toppings dialog...
            showToppingOptions();
        }

        private void btnRightToppings_Click(object sender, RoutedEventArgs e)
        {
            strPizzaToppingHeader = Globals.k_str_pizza_second_half;
            dblMultiplier = 0.5;
            // Show the toppings dialog...
            showToppingOptions();
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            lvToppings.Items.Clear();
            orderDataList.Clear();
        }
    }
}
